package com.kugou.miniapp.controller;

import com.kugou.miniapp.dao.UserMapper;
import com.kugou.miniapp.domain.Users;
import com.kugou.miniapp.service.UserService;
import com.kugou.miniapp.utils.MatchSocket;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper userMapper;
    @Autowired
    UserService userService;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("admin")
    public int admin(@RequestParam("password") String password){
        int c = userMapper.getAdminByPassword(password);
        if (c > 0){
            return c;
        }
        return 0;
    }


    @RequestMapping("get_friend")
    public List<Users> getFriend(String user_id) throws Exception {
        user_id = user_id.substring(0, 20);
        List<Users> friends = userService.getFriend(user_id);
        return friends == null? new ArrayList<>():friends;
    }

    @RequestMapping("get_outline_userinfo")
    public Users getOutLineUserInfo(@RequestParam("user_id")String user_id) throws Exception {
        user_id = user_id.substring(0, 20);
        return userService.getOutLineUserInfo(user_id);
    }

    @RequestMapping("friend")
    public void friend(@RequestParam("user_id") String user_id,@RequestParam("room_id") String room_id,@RequestParam("ack") boolean ack){
        user_id = user_id.substring(0, 20);
        Map<String, MatchSocket> room = MatchSocket.build.get(room_id);
        MatchSocket matchSocket_me = room.get(user_id);
        MatchSocket matchSocket_his = null;
        //获取另外一个socket
        for (String uid: room.keySet()){
            if (!uid.equals(user_id)){
                matchSocket_his = room.get(uid);
            }
        }
        if (ack){
            matchSocket_me.ack = 1;
            //判断两个socket
            if (matchSocket_me.ack == 1&&matchSocket_his.ack == 1){//添加好友
                userService.beFriend(matchSocket_me.user_id, matchSocket_his.user_id);
                Map<String, String> msg_map = new HashMap<>();
                msg_map.put("type", "friend");
                msg_map.put("msg", "yes");
                //向浏览器发送好友添加成功的信息
                matchSocket_me.session.getAsyncRemote().sendText(JSONObject.fromMap(msg_map).toString());
                matchSocket_his.session.getAsyncRemote().sendText(JSONObject.fromMap(msg_map).toString());
            }

        }else {
            matchSocket_me.ack = -1;
            Map<String, String> msg_map = new HashMap<>();
            msg_map.put("type", "friend");
            msg_map.put("msg", "no");
            //向浏览器发送好友添加失败的信息
            matchSocket_me.session.getAsyncRemote().sendText(JSONObject.fromMap(msg_map).toString());
            matchSocket_his.session.getAsyncRemote().sendText(JSONObject.fromMap(msg_map).toString());
        }

    }

    @RequestMapping("get_room_user_info")
    public Map<String, MatchSocket> getRoomUserInfo(String room_id){
        Map<String, MatchSocket> room = MatchSocket.build.get(room_id);
        return room;
    }

    @RequestMapping("/upload_user_info")
    public String addUser(Users user) throws Exception {
        if (user == null){
            logger.warn("user == null");
            throw new Exception("upload user can't be null。 please checkout the argument");
        }
        user.setUser_id(user.getUser_id().substring(0, 20));
        try {
            if (userService.getUserByUserId(user.getUser_id())==null){
                userService.addUser(user);
            }else {
                userService.updateUser(user);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("upload_user_info 发生错误");
            return "upload_user_info fail 发生错误";
        }
        return "success";
    }

    /**
     * 删除好友
     * @param my_user_id
     * @param his_user_id
     * @return
     * @throws Exception
     */
    @RequestMapping("del_friend")
    public int delHis(@RequestParam("my_user_id")String my_user_id, @RequestParam("his_user_id")String his_user_id) throws Exception {
        my_user_id = my_user_id.substring(0, 20);
        his_user_id = his_user_id.substring(0, 20);
        int count = userService.delFriend(my_user_id, his_user_id);
        if (count == 0){
            throw new Exception("删除失败， 不存在该记录");
        }
        return count;
    }

    @RequestMapping("/get")
    public String getall(){
        List<Users> users = userMapper.getAllUsers();
        for(Users user: users){
            logger.info(user.toString());
        }
        return "asd";
    }
}
